package com.wcards.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wcards.service.UserInfoService;
import com.wcards.config.JWT;
import com.wcards.config.MD5;
import com.wcards.config.R;
import com.wcards.dto.PasswordDTO;
import com.wcards.entity.UserInfo;
import com.wcards.mapper.UserInfoMapper;
import com.wcards.utils.ConstantUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author 大黑
 */
/*
用户信息表
 */
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private UserInfoService userInfoService;


    /*
    生成token,添加到Session中
     */
    public String findToken(UserInfo userInfo, HttpServletRequest request) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userName", userInfo.getUserName());
        claims.put("userId", userInfo.getUserId());
        String token = JWT.Tokenget(claims);
        request.getSession().setAttribute("token", token);
        return token;
    }

    /*
    登录接口逻辑
     */
    @Override
    public R<String> userLogin(UserInfo userInfo, HttpServletRequest request) {
        //密码加密
        String password = MD5.MD5s(userInfo.getUserPassword());
        //查看是否存在该用户
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getPhone, userInfo.getPhone());
        UserInfo userInfo1 = userInfoService.getOne(wrapper);
        //存在验证身份:0是用户，1是管理员
        if (userInfo1 != null) {
            //判断用户账号是否禁用
            if (userInfo1.getUserStatus() == 1) {
                //验证密码成功
                if (userInfo1.getUserPassword().equals(password)) {
                    //将Id和用户名放在Session中
                    request.getSession().setAttribute("userId", userInfo1.getUserId());
                    request.getSession().setAttribute("userName", userInfo1.getUserName());
                    //添加负载生成token
                    return R.success(findToken(userInfo1, request), userInfo1.getUserRole(), userInfo1.getUserName(), userInfo1.getUserId());
                } else {
                    return R.error("密码错误", 401);
                }
            } else {
                return R.error("该账号已被禁用", 401);
            }
        }
        return R.error("账号不存在", 401);
    }

    /*
    用户注册
     */
    @Override
    public R<String> register(UserInfo userInfo) {
        //判断手机号是否存在
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getPhone, userInfo.getPhone());
        UserInfo userInfo1 = userInfoService.getOne(wrapper);
        if (userInfo1 == null) {
            //密码进行MD5加密
            String password = userInfo.getUserPassword();
            userInfo.setUserPassword(MD5.MD5s(password));
            //默认头像
            userInfo.setHeadSculpture("0c536501-06f3-4c02-ba3f-00abfdd8d1ba.jpg");
            //随机用户名
            String userName = ConstantUtils.REGISTER_USER_NAME + UUID.randomUUID();
            userInfo.setUserName(userName);
            userInfo.setUserStatus(1);
            userInfo.setUserRole(0);
            userInfoService.save(userInfo);
            return R.success("注册成功");
        }
        return R.error("该手机号已注册", 401);
    }

    /*
    用户注销
     */
    @Override
    public R<String> logOut(Integer userId) {
        userInfoService.removeById(userId);
        return R.success("注销成功");
    }

    /*
    用户修改基本信息
     */
    @Override
    public R<String> updateIdentity(UserInfo userInfo) {
        userInfoService.updateById(userInfo);
        return R.success(userInfo.getHeadSculpture());
    }

    /*
    用户修改密码
     */
    @Override
    public R<String> updatePassword(PasswordDTO passwordDTO) {
        //获取要修改密码的用户
        UserInfo userInfo = userInfoService.getById(passwordDTO.getUserId());
        String oldPassword = MD5.MD5s(passwordDTO.getOdlPassword());//旧密码加密，对比数据库
        String newPassword = MD5.MD5s(passwordDTO.getNewPassword());
        if (userInfo.getUserPassword().equals(oldPassword)) {//检查旧密码是否正确
            if (!oldPassword.equals(newPassword)) {//检查新密码是否和旧密码一致
                if (passwordDTO.getNewPassword().equals(passwordDTO.getConfirmPassword())) {//检查两次密码是否相同
                    userInfo.setUserPassword(newPassword);
                    userInfoService.updateById(userInfo);
                    return R.success("密码修改成功");
                } else {
                    return R.error("请保证新密码和确定密码一致", 401);
                }
            } else {
                return R.error("新密码应该和旧密不一致", 401);
            }
        }
        return R.error("旧密码错误", 401);
    }

    /*
    分页查看用户
     */
    @Override
    public R<Page<UserInfo>> findUsers(Integer pageSize, Integer pageNumber, String phone, String userName, Integer userStatus) {
        Page<UserInfo> pageInfo = new Page<>(pageNumber, pageSize);
        //首先看是不是查看全部状态
        if (userStatus != null && userStatus.equals(5)) {
            LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<UserInfo>()
                    //判断名字和电话是否为空，最后过滤掉管理员
                    .like(StringUtils.isNotEmpty(userName), UserInfo::getUserName, userName)
                    .like(StringUtils.isNotEmpty(phone), UserInfo::getPhone, phone)
                    .eq(UserInfo::getUserRole, 0);
            userInfoService.page(pageInfo, wrapper);
            return R.success(pageInfo);
        }
        //根据名字，电话，状态条件模糊查询，最后过滤掉管理员
        LambdaQueryWrapper<UserInfo> wrapper1 = new LambdaQueryWrapper<UserInfo>()
                .like(StringUtils.isNotEmpty(userName), UserInfo::getUserName, userName)
                .like(StringUtils.isNotEmpty(phone), UserInfo::getPhone, phone)
                .like(null != userStatus, UserInfo::getUserStatus, userStatus)
                .eq(UserInfo::getUserRole, 0);
        userInfoService.page(pageInfo, wrapper1);
        return R.success(pageInfo);
    }

    /*
    启用禁用用户
     */
    @Override
    public R<String> updateStates(Integer userId) {
        UserInfo userInfo = userInfoService.getById(userId);
        //三目运算：将状态0改为1,1改为0
        userInfo.setUserStatus(userInfo.getUserStatus().equals(0) ? 1 : 0);
        userInfoService.updateById(userInfo);
        //0改为1：启用，1改为0：禁用
        String msg = userInfo.getUserStatus().equals(0) ? "禁用" : "启用";
        return R.success(msg + "成功");
    }

    /*
    根据用户Id进行查询
     */
    @Override
    public R<UserInfo> findById(Integer userId) {
        return R.success(userInfoService.getById(userId));
    }

    /*
    查看所有的用户
     */
    @Override
    public R<Page<UserInfo>> findAllUsers(Integer pageSize, Integer pageNumber) {
        Page<UserInfo> pageInfo = new Page<>(pageNumber, pageSize);
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserRole, 0);
        userInfoService.page(pageInfo, wrapper);
        return R.success(pageInfo);
    }

}
